package com.chinanet.repository.faultanticipate;


import com.chinanet.entry.faultanticipate.Branch;
import com.chinanet.entry.faultanticipate.QBranch;
import com.querydsl.core.types.dsl.StringPath;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer;
import org.springframework.data.querydsl.binding.QuerydslBindings;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;

public interface BranchRepository extends PagingAndSortingRepository<Branch, Long> , QuerydslBinderCustomizer<QBranch>,QuerydslPredicateExecutor<Branch> {

    @RestResource(path = "detail", rel = "detail")
    @Query(value = "select * from branch where detail_id=:detailId and is_master=:isMaster", nativeQuery = true)
    Page<Branch> findByDetailAndIsMasterAndPageable(@Param("detailId") long detailId,@Param("isMaster") boolean isMaster, Pageable pageable);

    @Query(value = "select * from branch where detail_id=:detailId and is_master=:isMaster", nativeQuery = true)
    Branch findByDetailAndIsMaster(@Param("detailId") long detailId,@Param("isMaster") boolean isMaster);

    @RestResource(path = "clearMaster", rel = "clearMaster")
    @Transactional
    @Modifying
    @Query(value = "update branch set is_master = 0 where detail_id=:detailId", nativeQuery = true)
    Integer clearMaster(@Param("detailId") long detailId);

    @RestResource(path = "allDetail", rel = "allDetail")
    @Query(value = "select * from branch where detail_id=:detailId order by is_master desc", nativeQuery = true)
    Page<Branch> findByDetail(@Param("detailId") long detailId, Pageable pageable);
    // 过滤
    default void customize(QuerydslBindings bindings, QBranch branch) {
/*        bindings.bind(relation.name).first((path, value) -> path.contains(value));
        bindings.bind(relation.name).first((path, value) -> path.containsIgnoreCase(value));*/
        bindings.bind(String.class).first((StringPath path, String value) -> {
            // 中文乱码解决问题
            try {
                String newValue=new String(value.getBytes("iso-8859-1"),"utf-8");
                return  path.contains(newValue);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return  null;
            }
        });
    }
}